<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>视频课程管理</h3>
    </div>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane v-for="tab in tabList" :key="tab.name" :label="tab.label" :name="tab.name">
        <div class="question-content">
          <div class="left">
            <div class="car-model-list">
              <div
                v-for="(group, index) in carData"
                :key="index"
                :class="['car-model-item', { active: activeCarId === group.carId }]"
                @click="tabHandle(group)"
              >
                <div class="name">
                  <img src="@/assets/img/question.png" class="material-icon" />
                  <span>{{ group.carName }}</span>
                </div>
                <div class="count">{{ group.questionCount }}</div>
              </div>
            </div>
          </div>
          <div class="right">
            <el-row style="margin-top: 1.5rem; width: 100%">
              <div style="width: 100%">
                <el-form :model="searchForm" ref="searchFormRef" label-width="82px">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item label="关键字" prop="questionName">
                        <el-input v-model="searchForm.questionName" @blur="search" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="课程类型" prop="questionType">
                        <el-select
                          v-model="searchForm.questionType"
                          clearable
                          placeholder="请选择"
                          style="width: 100%"
                          @change="search"
                        >
                          <el-option
                            v-for="item in typeOptions_two"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          >
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="操作时间">
                        <el-date-picker
                          label="操作时间："
                          v-model="datavalue1"
                          type="datetimerange"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          format="YYYY-MM-DD HH:mm:ss"
                          date-format="YYYY/MM/DD ddd"
                          time-format="A hh:mm:ss"
                          @change="getTime"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
                <el-col>
                  <div style="display: flex; justify-content: space-between; margin-top: 20px">
                    <div>
                      <el-button @click="showDialog('add')" type="primary">新增课程</el-button>
                      <el-button type="danger" :disabled="!selectIds.length" @click="batchDel"
                        >批量删除</el-button
                      >
                    </div>
                    <div style="display: flex">
                      <el-upload
                        class="avatar-uploader"
                        :action="excelServer"
                        :headers="headers"
                        :show-file-list="false"
                        :on-success="handleImportSuccess"
                        :before-upload="beforeImportUpload"
                        style="margin-left: 20px"
                      >
                        <el-button type="primary">导入课程</el-button>
                      </el-upload>
                      <el-button style="margin-left: 20px" @click="handleDownloadTemplate"
                        >下载模板</el-button
                      >
                    </div>
                  </div>
                </el-col>
              </div>
            </el-row>

            <art-table
              :data="tableData"
              v-loading="tableLoading"
              :currentPage="pageNum"
              :pageSize="pageSize"
              :total="pageTotal"
              @current-change="currentchange"
              @size-change="sizechange"
              @selection-change="handleSelectionChange"
            >
              <template #default>
                <el-table-column type="selection" width="55" />
                <el-table-column label="ID" prop="id" width="100" #default="scope">
                  {{ scope.row.questionId != 0 ? scope.row.questionId : scope.row.id }}
                </el-table-column>
                <el-table-column label="排序" prop="sort" width="100" />
                <!-- 视频内容 -->
                <el-table-column label="课程标题" prop="questionName" width="400">
                  <template #default="scope">
                    <div class="title_box">
                      <div class="title_box_right">
                        <div class="bankcont_title">
                          <div class="bankcont_title_text">{{ scope.row.questionName }}</div>
                        </div>
                        <div style="clear: both"></div>
                        <!-- 视频类型 -->
                        <div class="cartcont">
                          <el-button round size="small">
                            {{
                              `${scope.row.carModelList[0].carName}（${scope.row.carModelList[0].carTypes}）`
                            }}
                          </el-button>
                        </div>
                        <!-- 视频类型 -->
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="封面图" prop="videourl" width="300">
                  <template #default="scope">
                    <div @click="handlePreview(scope.row)" style="cursor: pointer">
                      <img :src="scope.row.questionImg" style="width: 100px" />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="题型">
                  <template #default="scope">
                    <el-button round size="small">
                      {{
                        scope.row.questionType === 3
                          ? '实拍讲解'
                          : scope.row.questionType === 4
                            ? '考点视频'
                            : ''
                      }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="视频描述" prop="answer" width="300" />
                <!-- 视频链接 -->
                <el-table-column #default="scope" label="启用状态">
                  <el-switch
                    v-model="scope.row.isDisplay"
                    :active-value="1"
                    :inactive-value="2"
                    @click="editisDisplay(scope.row.id, scope.row)"
                  />
                </el-table-column>

                <el-table-column label="操作时间" prop="createTime">
                  <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="150">
                  <template #default="scope">
                    <button-table type="edit" @click="buttonMoreClick(scope.row)" />
                    <button-table type="delete" @click="deleteRole(scope.row.id)" />
                  </template>
                </el-table-column>
              </template>
            </art-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增视频' : '编辑视频'"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" :rows="3" />
        </el-form-item>
        <el-form-item label="科目类型">
          <el-radio-group v-model="form.categoryId" :disabled="true">
            <el-radio value="1">科目一</el-radio>
            <el-radio value="2">科目二</el-radio>
            <el-radio value="3">科目三</el-radio>
            <el-radio value="4">科目四</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label=" 车型" prop="carIds">
          <el-select v-model="form.carIds" placeholder="请选择车型" style="width: 240px">
            <el-option
              v-for="item in carsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程类型" prop="questionType">
          <el-select v-model="form.questionType" placeholder="请选择课程类型" style="width: 240px">
            <el-option
              v-for="item in typeOptions_two"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程标题" prop="questionName">
          <el-input v-model="form.questionName" />
        </el-form-item>
        <el-form-item label="封面图" prop="questionImg">
          <el-input v-model="form.questionImg" style="display: none"></el-input>

          <el-upload
            class="avatar-uploader"
            :action="server"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleImgSuccess"
            :before-upload="beforeImgUpload"
          >
            <el-image
              v-if="form.questionImg"
              :src="form.questionImg"
              class="avatar"
              fit="contain"
            ></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"
              ><el-icon> <Plus /> </el-icon
            ></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频课程" prop="videoUrl">
          <el-input v-model="form.videoUrl">
            <template #append>
              <el-upload
                class="video-uploader"
                :action="server"
                :headers="headers"
                :show-file-list="false"
                :on-error="handleError"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                accept="video/*"
              >
                <el-button style="color: #2b8dfa" type="primary">点击上传</el-button>
              </el-upload>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="视频描述" prop="answer">
          <el-input v-model="form.answer" type="textarea" :rows="5" placeholder="请输入视频描述" />
        </el-form-item>
        <el-form-item label="状态" prop="isDisplay">
          <el-switch v-model="form.isDisplay" :active-value="1" :inactive-value="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="videoDialogVisible"
      width="60%"
      :destroy-on-close="true"
      class="video-dialog"
      :close-on-click-modal="false"
    >
      <template #header>
        <h2>{{ previewTitle }}</h2>
      </template>

      <template #default>
        <video
          v-if="videoDialogVisible"
          :src="previewSrc"
          controls
          autoplay
          style="width: 100%; height: auto"
        />
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { cardsType } from '@/api/userStudentsApi'
  import {
    addupdateList,
    putquestioncategory,
    getupdateList,
    delquestionlist,
    downQuestionExcel,
    getStatData
  } from '@/api/questionbank'

  const userStore = useUserStore()
  let server = `${import.meta.env.VITE_API_URL}files`
  let excelServer = `${import.meta.env.VITE_API_URL}ds-question/importXlsx`
  let { accessToken } = userStore
  const headers = { Authorization: 'Bearer ' + accessToken, store_id: localStorage.getItem('lty-store-id') }

  const dialogVisible = ref(false)
  const formRef = ref<FormInstance>()
  const activeCarId = ref('0')

  interface carItem {
    carId: string
    carName: string
    questionCount: number
  }
  const carInfo = ref<any[]>([])
  const carData = ref<carItem[]>([])

  const activeName = ref<string>('1')

  const handleClick = (e: any) => {
    searchForm.categoryId = e === '0' ? '' : e
    form.categoryId = e === '0' ? '' : e
    carData.value = carInfo.value.find((ele: any) => ele.categoryId === e)?.carStatDataList || []
    getData()
  }

  const tabList = [
    { label: '科目一', name: '1' },
    { label: '科目二', name: '2' },
    { label: '科目三', name: '3' },
    { label: '科目四', name: '4' }
  ]

  const rules = reactive<FormRules>({
    sort: [{ required: true, message: '请输入正确排序', trigger: 'blur' }],
    answer: [{ required: true, message: '请输入视频描述', trigger: 'blur' }]
  })

  const form = reactive({
    id: '',
    sort: '1',
    questionType: '',
    videoUrl: '',
    carIds: '',
    questionName: '',
    categoryId: '1',
    answer: '',
    isDisplay: 1,
    questionImg: ''
  })

  const dialogType = ref('add')

  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
      form.id = row.id
      form.sort = row.sort
      form.videoUrl = row.videoUrl
      form.questionType = String(row.questionType)
      form.answer = row.answer
      form.isDisplay = row.isDisplay
      form.questionImg = row.questionImg
      form.questionName = row.questionName
      form.carIds = row.carIds
    } else {
      form.id = ''
      form.isDisplay = 1
      form.videoUrl = ''
      form.questionType = ''
      form.answer = ''
      form.questionImg = ''
      form.questionName = ''
      form.carIds = ''
    }
  }

  const buttonMoreClick = (row: any) => {
    showDialog('edit', row)
  }

  const tabHandle = (e: any) => {
    searchForm.carId = e.carId != 0 ? e.carId : ''
    activeCarId.value = e.carId
    getData()
  }

  const deleteRole = (id: number) => {
    ElMessageBox.confirm('确定删除该题库吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(() => {
      handleDelete(String(id))
    })
  }
  async function handleDelete(id: string) {
    const res = await delquestionlist.delquestionlistId(id)
    if (res.code == '00000') {
      ElMessage.success('删除成功')
      await getData()
      getStatcInfo()
    }
  }

  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid) => {
      if (valid) {
        const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
        ElMessage.success(message)
        dialogVisible.value = false
        if (dialogType.value === 'add') {
          addFunction()
        } else {
          editFunction()
        }
      }
    })
  }
  async function addFunction() {
    try {
      dialogVisible.value = true
      const { id, ...formWithoutId } = form
      console.log(formWithoutId, 'formWithoutId')
      const res = await addupdateList.addupdateId({
        ...formWithoutId
      })
      if (res.code === '00000') {
        ElMessage.success('新增成功')
        getData()
        getStatcInfo()
      }
    } catch (e) {
    } finally {
      dialogVisible.value = false
    }
  }

  async function editFunction() {
    try {
      dialogVisible.value = true
      const res = await putquestioncategory.putquestioncategoryId(form.id, {
        ...form
      })
      if (res.code === '00000') {
        ElMessage.success('编辑成功')
        getData()
      }
    } catch (e) {
    } finally {
      dialogVisible.value = false
    }
  }
  async function editisDisplay(id: any, row: any) {
    try {
      Object.assign(form, {
        isDisplay: row.isDisplay,
        sort: row.sort,
        videoUrl: row.videoUrl,
        questionType: row.questionType,
        answer: row.answer,
        questionImg: row.questionImg,
        questionName: row.questionName,
        carIds: row.carIds
      })
      console.log(form, 'form===')
      const res = await putquestioncategory.putquestioncategoryId(id, {
        ...form
      })
      if (res.code === '0') {
        getData()
      }
    } catch (e) {
    } finally {
      await getData()
    }
  }

  const formatDate = (date: string) => {
    return new Date(date)
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      .replace(/\//g, '-')
  }

  interface TableData {
    id: string
    bankcont_title: string
    date: string
    sort: string
    switchvalue: boolean
    videourl: string
    imgurl: string
    type: any
    desc: string
    subject: string
  }
  function getTime(timeArr: string[]) {
    searchForm.startCreateTime = timeArr[0]
    searchForm.endCreateTime = timeArr[1]
    getData()
  }

  // 使用所有题库列表的ref
  let tableData = ref<TableData[]>([])

  //搜索刷新等
  const search = () => {
    getData()
  }

  const searchFormRef = ref<FormInstance>()
  const searchForm = reactive({
    questionName: '',
    questionType: '',
    carId: '',
    startCreateTime: '',
    endCreateTime: '',
    categoryId: ''
  })
  interface carsItem {
    value: string
    label: string
    total: number
  }
  const carsList = ref<carsItem[]>([])
  const getCardsTypeList = async () => {
    const res = await cardsType()
    carsList.value = res.data.map((e: any) => {
      return {
        value: e.value,
        label: `${e.label}（${e.tag}）`
      }
    })
  }
  const typeOptions_two = [
    {
      value: '3',
      label: '实拍讲解'
    },
    {
      value: '4',
      label: '考点视频'
    }
  ]
  const datavalue1 = ref('') //创建时间：
  //上传图片

  const beforeImportUpload = (file: any) => {
    const isEcxel =
      file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    const isLt50 = file.size / 1024 / 1024 < 50

    if (!isEcxel) {
      ElMessage.error('只能上Excel文件!')
      return false
    }
    if (!isLt50) {
      ElMessage.error('大小不能超过50MB!')
      return false
    }
    return true
  }

  const handleImportSuccess = (e: any) => {
    getData()
    ElMessage.success('导入成功')
  }
  async function handleDownloadTemplate() {
    const res = await downQuestionExcel({
      categoryId: form.id
    })
    if (res) {
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(res)
      link.download = '导入模板'
      link.style.display = 'none'
      document.body.appendChild(link)
      link.click()

      // 清理
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    }
  }

  let loadingMessage: ReturnType<typeof ElMessage> | null = null
  const handleError = () => {
    loadingMessage?.close()
    ElMessage({
      showClose: true,
      message: '上传失败，请稍后重试',
      type: 'error'
    })
  }
  const handleAvatarSuccess = (file: any) => {
    form.videoUrl = file.data.url

    loadingMessage?.close()
    ElMessage({
      showClose: true,
      message: '视频上传成功！',
      type: 'success'
    })
  }
  //上传限制大小格式等
  const beforeAvatarUpload = (file: any) => {
    loadingMessage = ElMessage({
      message: '视频上传中，请稍后...',
      type: 'info',
      duration: 0,
      showClose: false
    })

    const isVideo = file.type.startsWith('video/')
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isVideo) {
      ElMessage.error('只能上传视频文件')
      loadingMessage?.close()
      return false
    }
    if (!isLt100M) {
      ElMessage.error('视频大小不能超过 100MB')
      loadingMessage?.close()
      return false
    }

    return true
  }

  const previewSrc = ref('')
  const previewTitle = ref('')
  const videoDialogVisible = ref(false)
  function handlePreview(item: Record<string, any>) {
    videoDialogVisible.value = true
    previewSrc.value = item.videoUrl
    previewTitle.value = item.questionName
  }
  const handleImgSuccess = (file: any) => {
    form.questionImg = file.data.url
  }
  // 上传之前的处理
  const beforeImgUpload = (file: any) => {
    const isLt2M = file.size / 10240 / 10240 < 2
    if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
      ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传图片大小不能超过 20MB!!')
      return false
    }
  }

  const tableLoading = ref(false)
  const pageTotal = ref()
  const pageNum = ref(1)
  const pageSize = ref(50)
  //分页数据处理
  const currentchange = (val: number) => {
    pageNum.value = val
    getData() //请求用户列表接口
  }
  const sizechange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData() //请求用户列表接口
  }
  const filterEmptyValues = (obj: any) => {
    const result: any = {}
    for (const key in obj) {
      if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
        result[key] = obj[key]
      }
    }
    return result
  }
  async function getData() {
    try {
      tableLoading.value = true
      let params = filterEmptyValues(searchForm)
      let obj: Record<string, any> = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        questionType: searchForm.questionType,
        type: 1,
        ...params
      }
      const res = await getupdateList.getupdateId(obj)
      if (res.code === '00000') {
        tableData.value = res.data.list
        pageTotal.value = res.data.total
      }
    } catch (e) {
    } finally {
      tableLoading.value = false
    }
  }
  const getStatcInfo = async () => {
    const res = await getStatData({ type: 1 })
    carInfo.value = res.data
    carData.value =
      res.data.find((e: any) => e.categoryId === '1').carStatDataList || res.data[0] || null
  }

  const selectIds = ref<string[]>([])

  function handleSelectionChange(data: any[]) {
    selectIds.value = data.map((item) => item.id)
  }

  function batchDel() {
    ElMessageBox.confirm('确定批量删除吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(() => {
      let ids = selectIds.value.join(',')
      delImg(ids)
    })
  }

  async function delImg(id: string) {
    const res = await delquestionlist.delquestionlistId(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
      getStatcInfo()
    }
  }

  onMounted(() => {
    getCardsTypeList()
    getData()
    getStatcInfo()
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }
  }

  .tag-item + .tag-item {
    margin-left: 5px;
  }

  .label {
    float: left;
    margin: 0.5rem 0 0.5rem 1.5rem;
    display: inline;
  }

  .labellist .label:nth-child(1) {
    margin-left: 0;
  }

  .bankcont_title_text {
    float: left;
    margin-right: 1rem;
    font-weight: bold;
  }

  .label_sonli {
    color: #5d87ff;
  }

  .tag-item {
    margin-left: 5px;
  }

  .tagcontsize {
    color: #999;
  }

  .tagcontbigsize {
    margin-top: 0.5rem;
  }

  .cartcont {
    margin-top: 0.2rem;
  }

  .tableimg {
    width: 100%;
    height: 100%;
  }

  .title_box_left {
    float: left;
    width: 8rem;
    height: 4.5rem;
    border-radius: 0.5rem;
    overflow: hidden;
    margin-right: 1rem;
  }

  .title_box_right {
    float: right;
    float: left;
  }

  .bankcont_title_text {
    height: 2rem;
    margin-top: 0.3rem;
  }

  .columnvideo {
    border-radius: 0.5rem;
  }

  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  :deep(.el-textarea__inner) {
    height: 100px;
  }

  .question-content {
    display: flex;

    .left {
      width: 300px;
      margin-right: 20px;
      border-right: 1px solid #e4e7ed;

      .car-model-list {
        width: 300px;
      }

      .car-model-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 10px;
        font-size: 14px;
        cursor: pointer;
        transition: background 0.2s;

        .name {
          display: flex;
          align-items: center;

          .material-icon {
            width: 24px;
            height: 24px;
            margin-right: 6px;
          }
        }
      }

      .car-model-item:hover {
        background-color: #eff8ec;
      }

      .car-model-item.active {
        color: var(--el-color-primary);
        background-color: #eff8ec;
        border-right: 2px solid var(--el-color-primary);
      }

      .car-model-item .count {
        color: #999;
        font-size: 13px;
      }
    }

    .right {
      flex: 1;
      height: 100%;
      padding-top: 10px;
      overflow-x: auto;
    }
  }
</style>
